import {Component, OnInit} from "@angular/core";
import {Contact} from "../../models/contact";
import {ContactService} from "../../services/contact.service";
import {UserService} from "../../services/user.service";

@Component({
  selector: 'app-contact',
  templateUrl: './contact.component.html',
  styleUrls: ['./contact.component.css']
})
export class ContactComponent implements OnInit {
  contact: Contact
  contacts: Contact[]

  msg = 'Loading contacts ...'
  userName = ''

  constructor(private contactService: ContactService, userService: UserService) {
    this.userName = userService.userName
  }

  ngOnInit() {
    this.contactService.getContacts().subscribe(contacts => {
      this.msg = ''
      this.contacts = contacts
      this.contact = contacts[0]
    })
  }

  next() {
    let contacts = this.contacts
    let ix = 1 + contacts.indexOf(this.contact)
    if (ix >= contacts.length) {
      ix = 0
    }
    this.contact = contacts[ix]
  }

  onSubmit() {
    this.displayMessage(`Saved ${this.contact.name}`)
  }

  newContact() {
    this.displayMessage('New contact')
    this.contact = {id: 42, name: ''}
    this.contacts.push(this.contact)
  }

  private displayMessage(msg: string) {
    this.msg = msg
    setTimeout(()=> {
      this.msg = ''
    }, 1500)
  }
}
